package com.xiaoxin.experience.demo;

import javax.swing.filechooser.FileSystemView;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * @author xiaoxin
 */
public class Main
{
    public static void main(String[] args) throws Exception
    {
        String targetDir = "D:\\temp";
        String collectDir = "C:\\Users\\hh\\Desktop\\新建文件夹";
        String ext = ".mp4";
        File targetDirFile = new File(targetDir);

        // 获取要解压的文件列表
        File[] files = targetDirFile.listFiles((dir,name)->name.endsWith(".zip"));
        if (files != null)
        {
            for (File file : files)
            {
                System.out.println("unzip file: " + file.getAbsolutePath());
                unzip(file.getAbsolutePath(),targetDir);
                String s = trimExt(file.getAbsolutePath());
                String currentDirName = getCurrentDirName(s);
                File targetFile = findFile(s);
                if (targetFile != null)
                {
                    rename(targetFile.getAbsolutePath(),collectDir + File.separator + currentDirName + ext);
                    System.out.println(s);
                    removeDir(s);
                    deleteFile(file);
                    break;
                }
                else
                {
                    System.out.println(file.getAbsolutePath() + " not found file: ");
                }
            }
        }
    }

    private static void removeDir(String path)
    {
        deleteFile(path);
    }

    public static void deleteFile(String dir)
    {
        File dirFile = new File(dir);
        File[] files = dirFile.listFiles();
        if (files != null)
        {
            for(File file : files)
            {
                if (file.isDirectory())
                {
                    deleteFile(file.getAbsolutePath());
                    continue;
                }
                deleteFile(file);
            }
        }
        // 目录为空或者只是一个文件
        deleteFile(dirFile);
    }

    public static void deleteFile(File file)
    {
        if (Objects.isNull(file))
        {
            return;
        }
        try
        {
            Files.delete(file.toPath());
        }
        catch (Exception e)
        {
            System.out.println("delete file[ " + file.getName() + "] fail: ");
        }
    }

    private static String trimExt(String filePath)
    {
        return filePath.substring(0,filePath.lastIndexOf("."));
    }

    private static void rename(String sourceFile, String targetDir)
            throws IOException
    {
        File file = new File(sourceFile);
        Files.move(Paths.get(file.getAbsolutePath()),Paths.get(targetDir), StandardCopyOption.REPLACE_EXISTING);
    }

    private static String getParentName(String path)
    {
        File file = new File(path);
        return file.getParentFile().getName();
    }

    private static String getCurrentDirName(String path)
    {
        return path.substring(path.lastIndexOf(File.separator) + 1);
    }

    private static File findFile(String path)
    {
        File file = new File(path);
        if (file.exists())
        {
            if(file.isDirectory())
            {
                File[] files = file.listFiles();
                if (files == null)
                {
                    return null;
                }
                List<File> dirFile = new ArrayList<>();
                for (File innerFile : files)
                {
                    if (innerFile.isFile())
                    {
                        if (isVideoFile(innerFile))
                        {
                            return innerFile;
                        }
                    }
                    else
                    {
                        dirFile.add(innerFile);
                    }
                }
                for (File dir : dirFile)
                {
                    File file1 = findFile(dir.getAbsolutePath());
                    if (file1 != null)
                    {
                        return file1;
                    }
                }
            }
            else
            {
                if (isVideoFile(file))
                {
                    return file;
                }
            }
        }
        return null;
    }

    private static boolean isVideoFile(File file)
    {
        String lowercaseFileName = file.getName().toLowerCase();
        return lowercaseFileName.endsWith(".ts") || lowercaseFileName.endsWith(".mp4") || lowercaseFileName.endsWith(".avi") || lowercaseFileName.endsWith(".mkv");
    }

    private static void unzip(String zipFilePath, String destDirectory) throws IOException
    {
        long start = System.currentTimeMillis();
        try
        {
            File destDir = new File(destDirectory);
            if (!destDir.exists())
            {
                boolean mkdirs = destDir.mkdirs();
                if (!mkdirs)
                {
                    System.out.println("创建目录(mkdirs)失败: " + destDirectory);
                    return;
                }
            }
            try (FileInputStream fis = new FileInputStream(zipFilePath);
                 ZipInputStream zis = new ZipInputStream(fis, Charset.forName("GBK")))
            {
                ZipEntry entry = zis.getNextEntry();

                while (entry != null)
                {
                    String filePath = destDirectory + File.separator + entry.getName();
                    if (!entry.isDirectory())
                    {
                        extractFile(zis, filePath);
                    }
                    else
                    {
                        File dir = new File(filePath);
                        boolean mkdir = dir.mkdir();
                        if (!mkdir)
                        {
                            System.out.println("创建目录(mkdir)失败: " + filePath);
                            return;
                        }
                    }
                    entry = zis.getNextEntry();
                }
                zis.closeEntry();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        System.out.println(zipFilePath + " 耗时：" + (System.currentTimeMillis() - start) + "ms");
    }

    private static void extractFile(ZipInputStream zis, String filePath) throws IOException
    {
        try (BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(Paths.get(filePath))))
        {
            byte[] bytesIn = new byte[4096];
            int read;
            while ((read = zis.read(bytesIn)) != -1)
            {
                bos.write(bytesIn, 0, read);
            }
        }
    }

    private void getDisk()
    {
        File[] _files = File.listRoots();//全部盘符 临时变量
        File[] files = new File[10];//最大10个本地磁盘
        int i = 0;//索引变量
        //过滤掉非"本地磁盘"类型的磁盘 by xdj 20121016
        FileSystemView fileSystemView = FileSystemView.getFileSystemView();// 获取FileSystemView对象
        for (File file : _files)
        {
            // 获取磁盘的类型描述信息
            String diskType = fileSystemView.getSystemTypeDescription(file);
            //盘符类型包括：本地磁盘、可移动磁盘、CD 驱动器等
            if (diskType.equals("本地磁盘"))
            {
                files[i++] = file;//只保留本地磁盘。
            }
        }
        for (File file : files)
        {
            if (file != null)
            {
                System.out.println(file.getPath());
            }
        }
    }

}
